<template>
  <div>
    <div class="clearfix">
      <a-button class="w-float-right" type="primary" size="small" :loading="loading" @click="saveBtnClick">
        保存
      </a-button>
      <span class="w-float-right">&nbsp;&nbsp;</span>
      <a-button
        v-if="$route.query.id"
        class="w-float-right"
        type="primary"
        size="small"
        @click="previewClick"
      >
        预览
      </a-button>
    </div>
    <br>
    <a-form :form="form" :label-col="{ span: 1 }" :wrapper-col="{ span: 23 }">
      <a-form-item label="名称">
        <a-input
          v-decorator="['name', { rules: [{ required: true, message: '请输入' }], initialValue: model ? model.name : '' }]"
          placeholder="请输入名称..."
        />
      </a-form-item>
      <a-form-item label="链接">
        <a-input
          v-decorator="['url', { initialValue: model ? model.url : '' }]"
          placeholder="请输入链接地址..."
        />
      </a-form-item>
      <a-form-item label="封页" prop="cover">
        <w-up-image ref="WUpImage" :souce-url="cover" />
      </a-form-item>
      <a-form-item label="类型" prop="type">
        <a-input
          v-decorator="['type', { rules: [{ required: true, message: '请输入' }], initialValue: model ? model.type : '' }]"
        >
          <a-select slot="addonAfter" v-model="optionType" style="width: 80px" @change="typeChange">
            <a-select-option v-for="(v, k) in types" :key="k" :value="v">
              {{ v }}
            </a-select-option>
          </a-select>
        </a-input>
      </a-form-item>
      <a-form-item label="描述">
        <a-input
          v-decorator="['describe', { initialValue: model ? model.name : '' }]"
          type="textarea"
          placeholder="请输入描述..."
        />
      </a-form-item>
    </a-form>
    <w-editor ref="WEditer" :imgbtn="true" :savebtn="true" :zoom="true" @save="saveBtnClick" />
  </div>
</template>

<script lang="ts">
import { Vue, Component } from 'vue-property-decorator'
import { Api, Admin } from '@/config/api'
import WUpImage, { OssImageUpType } from '@/components/global/imageUp/oss'
import WEditor, { MarkedComType } from '@/components/global/marked'
import { WrappedFormUtils } from 'ant-design-vue/types/form/form'
import WPackage from '@/models/package'

@Component({
  name: 'AdminWebPackageAdd',
  layout: 'admin',
  components: {
    WUpImage,
    WEditor
  },
  async asyncData ({ app, route }) {
    const { $wAxios } = app
    const arr = [$wAxios.$get(Api.package.types)]
    if (route.query.id) {
      arr.push($wAxios.$get(`${Api.package.detail}${route.query.id}`))
    }
    const data = await Promise.all(arr)
    const [types, detail] = data
    const reData: any = {
      types
    }
    if (detail) {
      reData.model = detail
      reData.optionType = detail.type
      reData.cover = detail.cover
    }
    return reData
  },
  head () {
    return {
      title: '封装'
    }
  },
  data () {
    return {
      form: this.$form.createForm(this, { name: 'coordinated' })
    }
  }
})
export default class AdminWebPackageAdd extends Vue {
  form!: WrappedFormUtils;
  optionType = null;
  model: WPackage | null = null;
  cover = '';
  loading = false

  mounted () {
    if (this.model) {
      (this.$refs.WEditer as MarkedComType).setData(this.model.content)
    }
  }

  typeChange (val: string) {
    this.form.setFieldsValue({
      type: val
    })
  }

  check () {
    return new Promise((resolve, reject) => {
      (this.$refs.WUpImage as OssImageUpType)
        .upImage()
        .then((data) => {
          this.cover = data
          this.form.validateFields((err, values) => {
            if (!err) {
              resolve(values)
            } else {
              this.$message.error('请完成填写')
              reject(err)
            }
          })
        })
        .catch(() => {
          this.$message.error('请选择图片')
        })
    })
  }

  previewClick () {
    window.open(`/web/package/${this.$route.query.id}`)
  }

  saveBtnClick () {
    this.loading = true
    this.check().then((values: any) => {
      const p = {
        ...values,
        cover: this.cover,
        content: (this.$refs.WEditer as MarkedComType).getData()
      }
      const url = this.$route.query.id
        ? `${Admin.package.update}${this.$route.query.id}`
        : Admin.package.create
      const method = this.$route.query.id ? '$put' : '$post'
      this.$wAxios[method](url, p)
        .then((data) => {
          this.$message.success('成功')
          if (!this.$route.query.id) {
            this.$router.replace({
              path: '/admin/web/package/add',
              query: { id: data._id }
            })
          }
        })
        .catch(() => {}).finally(() => {
          this.loading = false
        })
    }).catch(() => {
      this.loading = false
    })
  }
}
</script>

<style scoped></style>
